package com.kfm.servlet;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;

@WebServlet("/resp-encoding")
public class RespEncodingServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("RespEncodingServlet.doGet()");

        // 设置响应头
//        response.setHeader("content-type", "text/plain;charset=utf-8");
//        response.setContentType("text/html;charset=utf-8");
//
//        PrintWriter writer = response.getWriter();
//
//        String html = """
//                <html>
//                    <head>
//                        <meta charset="utf-8">
//                        <title>响应编码</title>
//                        <style>
//                            body {
//                                background-color: #f1f1f1;
//                            }
//                            h1{
//                                text-align: center;
//                            }
//                            p{
//                                font-size: 20px;
//                                color: #333;
//                            }
//                        </style>
//                    </head>
//                    <body>
//                        <h1>响应编码</h1>
//                        <p>你好</p>
//                    </body>
//                </html>
//                """;
//
//        writer.write(html);

        // 响应文件
        String path = "D:\\temp\\car1.png";
        // 获取文件的 mime类型
        String mimeType = getServletContext().getMimeType(path);

        // 设置响应头
        response.setContentType(mimeType);

        // 下载文件设置响应头
        response.setHeader("content-disposition", "attachment;filename=car1.png");

        // 获取字节输出流
        ServletOutputStream outputStream = response.getOutputStream();

        // 读取文件
        try(FileInputStream fis = new FileInputStream(path);){
            // 写文件
            fis.transferTo(outputStream);
        }


    }
}
